package com.binance.routing.filter;


import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.binance.master.constant.Constant;
import com.binance.master.ribbon.support.RibbonFilterContextHolder;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;


@Component
@Slf4j
public class GrayFilter extends ZuulFilter {

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        // a filter has already forwarded
        // a filter has already determined serviceId
        return !ctx.containsKey(FilterConstants.FORWARD_TO_KEY) && !ctx.containsKey(FilterConstants.SERVICE_ID_KEY);
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        // header继续向下传递
        String grayEnvFlag = ctx.getRequest().getHeader(Constant.GRAY_ENV_HEADER);
        if (grayEnvFlag != null) {
            RibbonFilterContextHolder.getCurrentContext().setEnvFlag(grayEnvFlag);
        } else {
            // 正常环境标识
            ctx.addZuulRequestHeader(Constant.GRAY_ENV_HEADER, Constant.ENV_FLAG_NORMAL);
            RibbonFilterContextHolder.getCurrentContext().setEnvFlag(Constant.ENV_FLAG_NORMAL);
        }
        log.info("requestUri={},header={},envFlag={}", ctx.getRequest().getRequestURI(),
                ctx.getRequest().getHeader(Constant.GRAY_ENV_HEADER),
                RibbonFilterContextHolder.getCurrentContext().getEnvFlag());
        return null;
    }
}
